<template>
  <div class="auth-container">
    <!-- 彩色泡泡背景 -->
    <div class="bubbles">
      <span v-for="(bubble, index) in bubbles" :key="index" :style="bubbleStyle(bubble)"></span>
    </div>
    
    <div class="slider-container" :class="{ 'right-panel-active': isRegisterActive }">
      <!-- 登录表单（已修改为用户名登录） -->
      <div class="form-container sign-in-container">
        <div class="form-content">
          <h2>欢迎回来</h2>
          <p>请登录您的账户</p>
          <form @submit.prevent="handleLogin">
            <div class="input-group">
              <input type="text" placeholder="用户名" v-model="loginForm.username" required />
              <span v-if="loginErrors.username" class="error-message">{{ loginErrors.username }}</span>
            </div>
            <div class="input-group">
              <input type="password" placeholder="密码" v-model="loginForm.password" required />
              <span v-if="loginErrors.password" class="error-message">{{ loginErrors.password }}</span>
            </div>
            
            <button type="submit" class="auth-button">登录</button>
          </form>
          <a href="#" class="forgot-password">忘记密码?</a>
        </div>
      </div>

      <!-- 注册表单（保持不变） -->
      <div class="form-container sign-up-container">
        <div class="form-content">
          <h2>加入我们</h2>
          <p>创建新账户，发现更多精彩</p>
          <form @submit.prevent="handleRegister">
            <div class="input-group">
              <input type="text" placeholder="用户名" v-model="registerForm.username" required />
              <span v-if="registerErrors.username" class="error-message">{{ registerErrors.username }}</span>
            </div>
            <div class="input-group">
              <input type="email" placeholder="邮箱" v-model="registerForm.email" required />
              <span v-if="registerErrors.email" class="error-message">{{ registerErrors.email }}</span>
            </div>
            <div class="input-group">
              <input type="password" placeholder="密码" v-model="registerForm.password" required />
              <span v-if="registerErrors.password" class="error-message">{{ registerErrors.password }}</span>
            </div>
            <button type="submit" class="auth-button">注册</button>
          </form>
        </div>
      </div>

      <!-- 滑动面板（保持不变） -->
      <div class="overlay-container">
        <div class="overlay">
          <div class="overlay-panel overlay-left">
            <h2>欢迎回来</h2>
            <p>请登录您的账户</p>
            <button class="ghost auth-button" @click="togglePanel(false)">登录</button>
          </div>
          <div class="overlay-panel overlay-right">
            <h2>加入我们</h2>
            <p>创建新账户，发现更多精彩</p>
            <button class="ghost auth-button" @click="togglePanel(true)">注册</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus'
export default {
  name: 'AuthSlider',
  setup() {
    const router = useRouter();
    return {
      router
    };
  },
  data() {
    return {
      isRegisterActive: false,
      // 登录表单已修改为用户名+密码
      loginForm: {
        username: '',
        password: ''
      },
      registerForm: {
        username: '',
        email: '',
        password: ''
      },
      bubbles: Array(40).fill().map(() => ({
        size: Math.random() * 60 + 20, // 20-80px
        positionX: Math.random() * 100,
        positionY: Math.random() * 100,
        delay: Math.random() * 2,
        duration: Math.random() * 5 + 5,
        color: `hsla(${Math.random() * 360}, 80%, 70%, ${Math.random() * 0.4 + 0.2})`,
        blur: Math.random() * 2,
        drift: (Math.random() - 0.5) * 200
      })),
      loginErrors: {},
      registerErrors: {}
    }
  },
  methods: {
    togglePanel(isRegister) {
      this.isRegisterActive = isRegister;
    },
    async handleLogin() {
  this.loginErrors = {};
  if (!this.loginForm.username) {
      this.loginErrors.username = '用户名不能为空';
      return;
  }
  if (!this.loginForm.password) {
      this.loginErrors.password = '密码不能为空';
      return;
  }

  try {
      const response = await axios.get('http://localhost:8080/user/login', {
          params: {
              username: this.loginForm.username,
              password: this.loginForm.password
          }
      });

      console.log('登录响应:', response);

      if (response.data.code === 1) { 
          // 确保后端返回了userId和token
          const token = response.data.data.token || 'default-token';
          const userId = response.data.data.id || response.data.data.userId;
          
          if (!userId) {
              throw new Error('用户ID未返回');
          }
          
          localStorage.setItem('token', token);
          localStorage.setItem('userId', userId.toString()); // 确保存储为字符串
          
          ElMessage({
              message: '登录成功',
              type: 'success',
              duration: 1000,
              center: true
          });
          
          setTimeout(() => {
              this.router.push('/');
          }, 1000);
      } else {
          ElMessage({
              message: response.data.message || '登录失败',
              type: 'error',
              duration: 3000,
              center: true
          });
      }
  } catch (error) {
      console.error('登录错误:', error);
      let errorMessage = '登录失败';

      if (error.response) {
          errorMessage = error.response.data?.message || 
                         `错误代码: ${error.response.status}`;
      } else if (error.message) {
          errorMessage = error.message;
      }

      ElMessage({
          message: errorMessage,
          type: 'error',
          duration: 3000,
          center: true
      });
  }
},
  async handleRegister() {
  this.registerErrors = {};
  
  if (!this.registerForm.username) {
    this.registerErrors.username = '用户名不能为空';
  }
  if (!this.registerForm.email) {
    this.registerErrors.email = '邮箱不能为空';
  } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.registerForm.email)) {
    this.registerErrors.email = '请输入有效的邮箱地址';
  }
  if (!this.registerForm.password) {
    this.registerErrors.password = '密码不能为空';
  }
  
  if (Object.keys(this.registerErrors).length > 0) {
    return;
  }

  try {
    const response = await axios.post('http://localhost:8080/user/register', {
      username: this.registerForm.username,
      email: this.registerForm.email,
      password: this.registerForm.password
    });

    // 成功提示
    ElMessage({
      message: '注册成功，请登录',
      type: 'success',
      duration: 3000,
      center: true,
      showClose: true,
      customClass: 'register-success-message'
    });

    // 重置表单
    this.registerForm = {
      username: '',
      email: '',
      password: ''
    };
    
    // 切换到登录面板
    this.togglePanel(false);
    
  } catch (error) {
    console.error('注册错误:', error);
    
    let errorMessage = '注册失败，请稍后重试';
    if (error.response) {
      errorMessage = error.response.data?.message || 
                   `服务器错误: ${error.response.status}`;
    } else if (error.request) {
      errorMessage = '网络错误，请检查您的连接';
    }
    
    ElMessage({
      message: errorMessage,
      type: 'error',
      duration: 5000,
      center: true,
      showClose: true
    });
  }
},
    bubbleStyle(bubble) {
      return {
        width: `${bubble.size}px`,
        height: `${bubble.size}px`,
        left: `${bubble.positionX}%`,
        top: `${bubble.positionY}%`,
        background: bubble.color,
        filter: `blur(${bubble.blur}px)`,
        animationDelay: `${bubble.delay}s`,
        animationDuration: `${bubble.duration}s`,
        opacity: 0,
        '--drift': `${bubble.drift}px`
      }
    }
  }
}
</script>

<style scoped>
/* 样式部分完全保持不变 */
.auth-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #639cf1 0%, #fdfdfd 100%);
  font-family: 'Arial', sans-serif;
  position: relative;
  overflow: hidden;
}

.bubbles {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: 0;
  overflow: hidden;
}

.bubbles span {
  position: absolute;
  border-radius: 50%;
  box-shadow: 0 0 15px rgba(255, 255, 255, 0.4),
              0 0 30px rgba(255, 255, 255, 0.2);
  animation: floatBubbles linear infinite;
  will-change: transform;
}

@keyframes floatBubbles {
  0% {
    transform: translateY(100vh) translateX(0) scale(0.8);
    opacity: 0;
  }
  10% {
    opacity: 0.8;
    transform: translateY(90vh) translateX(0) scale(1);
  }
  90% {
    opacity: 0.8;
  }
  100% {
    transform: translateY(-100px) translateX(var(--drift)) scale(0.9);
    opacity: 0;
  }
}

.slider-container {
  position: relative;
  width: 768px;
  max-width: 90%;
  min-height: 480px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 15px;
  box-shadow: 0 14px 28px rgba(0, 0, 0, 0.1), 0 10px 10px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  z-index: 1;
  backdrop-filter: blur(4px);
  border: 1px solid rgba(255, 255, 255, 0.4);
}

/* 表单容器样式 */
.form-container {
  position: absolute;
  top: 0;
  height: 100%;
  transition: all 0.6s ease-in-out;
}

.sign-in-container {
  left: 0;
  width: 50%;
  z-index: 2;
}

.sign-up-container {
  left: 0;
  width: 50%;
  opacity: 0;
  z-index: 1;
}

.form-content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 0 50px;
  height: 100%;
  text-align: center;
}

h2 {
  font-weight: bold;
  margin: 0;
  color: #080808;
}

p {
  font-size: 14px;
  font-weight: 100;
  line-height: 20px;
  letter-spacing: 0.5px;
  margin: 15px 0 20px;
  color: #322e2e;
}

.input-group {
  margin-bottom: 15px;
  width: 100%;
}

input {
  background: rgba(255, 255, 255, 0.9);
  border: 1px solid #e0e0e0;
  padding: 12px 15px;
  width: 100%;
  border-radius: 8px;
  outline: none;
  transition: all 0.3s;
  font-size: 14px;
}

input:focus {
  border-color: #b388ff;
  box-shadow: 0 0 0 3px rgba(179, 136, 255, 0.2);
}

.forgot-password {
  color: #6a11cb;
  font-size: 12px;
  text-decoration: none;
  margin: 10px 0;
  display: inline-block;
  transition: all 0.3s;
}

.forgot-password:hover {
  text-decoration: underline;
  color: #7c4dff;
}

.auth-button {
  border-radius: 25px;
  border: none;
  background: linear-gradient(to right, #b47af1, #2575fc);
  color: white;
  font-size: 12px;
  font-weight: bold;
  padding: 12px 45px;
  letter-spacing: 1px;
  text-transform: uppercase;
  transition: all 0.3s;
  cursor: pointer;
  margin-top: 10px;
  box-shadow: 0 4px 15px rgba(106, 17, 203, 0.3);
}

.auth-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(106, 17, 203, 0.4);
}

.auth-button:active {
  transform: translateY(0);
}

.auth-button.ghost {
  background: transparent;
  border: 2px solid white;
  color: white;
}

.overlay-container {
  position: absolute;
  top: 0;
  left: 50%;
  width: 50%;
  height: 100%;
  overflow: hidden;
  transition: transform 0.6s ease-in-out;
  z-index: 100;
}

.overlay {
  background: linear-gradient(to right, #a8c4f7, #508ef8);
  color: white;
  position: relative;
  left: -100%;
  height: 100%;
  width: 200%;
  transform: translateX(0);
  transition: transform 0.6s ease-in-out;
}

.overlay-panel {
  position: absolute;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  top: 0;
  height: 100%;
  width: 50%;
  padding: 0 40px;
  transform: translateX(0);
  transition: transform 0.6s ease-in-out;
}

.overlay-left {
  transform: translateX(-20%);
}

.overlay-right {
  right: 0;
  transform: translateX(0);
}

/* 动画效果 */
.slider-container.right-panel-active .sign-in-container {
  transform: translateX(100%);
  opacity: 0;
}

.slider-container.right-panel-active .sign-up-container {
  transform: translateX(100%);
  opacity: 1;
  z-index: 5;
}

.slider-container.right-panel-active .overlay-container {
  transform: translateX(-100%);
}

.slider-container.right-panel-active .overlay {
  transform: translateX(50%);
}

.slider-container.right-panel-active .overlay-left {
  transform: translateX(0);
}

.slider-container.right-panel-active .overlay-right {
  transform: translateX(20%);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .slider-container {
    width: 95%;
    min-height: auto;
    flex-direction: column;
  }
  
  .form-container {
    position: relative;
    width: 100%;
    height: auto;
    padding: 30px 0;
  }
  
  .overlay-container {
    position: relative;
    left: 0;
    width: 100%;
    height: 200px;
  }
  
  .overlay {
    left: 0;
    width: 100%;
    height: 100%;
  }
  
  .overlay-panel {
    width: 100%;
    padding: 20px;
  }
  
  .bubbles span {
    display: none;
  }
}

.error-message {
  color: red;
  font-size: 12px;
  margin-top: 5px;
}
</style>